//
//  YFSearchController.m
//  SquashSpark
//
//  Created by Coollang on 2017/11/8.
//  Copyright © 2017年 Coollang-YF. All rights reserved.
//

#import "YFSearchController.h"
#import "YFSearchViewCell.h"
#import "UIView+JCDrawTool.h"
#import "DeviceInfo.h"
#import "YFSensorManager.h"
#import "PNChart.h"
#import "YFSectionHeadView.h"

NSString *const cellIndentifer = @"YFSearchViewCell";
#define kCenterViewWidth ((190 * kYFScreenWidth) / 375.0)


typedef enum : NSUInteger {
    kSearchStateStopScan,
    kSearchStateScan,
    kSearchStateSysData,
} kSearchState;


@interface YFSearchController ()<UITableViewDelegate,UITableViewDataSource>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UIView *centerView;
@property (weak, nonatomic) IBOutlet UIImageView *rotionImageView;
@property (nonatomic, strong) NSArray *lgPeripherals;
@property (weak, nonatomic) IBOutlet UIButton *startSearchButton;
@property (weak, nonatomic) IBOutlet UIImageView *highImagview;

@property (weak, nonatomic) IBOutlet UIView *progressSuperView;
@property (nonatomic, strong) PNCircleChart *progressView;
/** 时候停止旋转 */
@property (nonatomic, assign)BOOL stopRotation;

/** 当前选中的设备 */
@property (nonatomic, strong) LGPeripheral *selectPeriperal;

/** 搜索控制器当前状态 */
@property (nonatomic, assign) kSearchState searchState;

@end

@implementation YFSearchController{
    __block BOOL _shouldRefresh;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    _shouldRefresh = YES;
    self.title = @"Search For Sensor";
    [self setUpUI];
    [self registerNotification];
}
- (void)registerNotification
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleRefreshRssi:) name:kLGCentralManagerDidRefreshRssiNotification object:nil];
}
- (void)handleRefreshRssi:(NSNotification *)notification
{
    if (_shouldRefresh) {
        _shouldRefresh = NO;
        self.lgPeripherals = [self.lgPeripherals sortedArrayUsingComparator:^NSComparisonResult(LGPeripheral *obj1, LGPeripheral *obj2) {
            return obj1.countOfSignal < obj2.countOfSignal;
        }];
        [self.tableView reloadData];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            _shouldRefresh = YES;
        });
    }
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
     [self startScanPeripherals];
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [self endScanPeripherals];
}
- (void)setUpUI {
    self.startSearchButton.titleLabel.font = kOpenSansFont(OpenSansBold, 20);
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.backgroundColor = kSeparationLineColor;
    self.tableView.rowHeight = 50;
    self.tableView.tableHeaderView = [UIView new];
    [self.centerView clipsCornerRadius:kCenterViewWidth * 0.5 borderWidth:6 borderColor:kYellowGreenColor];
    
    self.progressView = [[PNCircleChart alloc] initWithFrame:CGRectMake(0, 0, kCenterViewWidth, kCenterViewWidth) total:@100 current:@0 clockwise:YES shadow:YES shadowColor:[UIColor colorWithWhite:1 alpha:0.4]];
    self.progressView.chartType = PNChartFormatTypePercent;
    self.progressView.strokeColor = kYellowGreenColor;
    self.progressView.lineWidth = @6;
    self.progressView.countingLabel.textColor = kTWhiteText;
    self.progressView.circle.lineCap = kCALineCapSquare;
    self.progressView.displayCountingLabel = YES;
    self.progressView.countingLabel.font = kOpenSansFont(OpenSansRegular, 20);
    [self.progressSuperView addSubview:self.progressView];
    self.progressSuperView.hidden = YES;
    self.progressView.showProgressAni = NO;
    [self.progressView strokeChart];
}

#pragma mark - 根据不同的状态切换不同的UI 效果
- (void)setSearchState:(kSearchState)searchState {
    _searchState = searchState;
    switch (searchState) {
        case kSearchStateStopScan:{
            self.stopRotation = YES;
            [self.startSearchButton setTitle:@"Searching" forState:UIControlStateNormal];
            [self.centerView clipsCornerRadius:kCenterViewWidth * 0.5 borderWidth:6 borderColor:kYellowGreenColor];
            self.rotionImageView.hidden = YES;
            self.progressSuperView.hidden = YES;
        }
            break;
        case kSearchStateScan:{
            self.rotionImageView.hidden = NO;
            [self.startSearchButton setTitle:@"Searching" forState:UIControlStateNormal];
            [self.centerView clipsCornerRadius:kCenterViewWidth * 0.5 borderWidth:0 borderColor:[UIColor clearColor]];
            self.stopRotation = NO;
            [self startRotaionImageView];
            self.progressSuperView.hidden = YES;
        }
            break;
        case kSearchStateSysData:{
            self.stopRotation = YES;
            [self.centerView clipsCornerRadius:kCenterViewWidth * 0.5 borderWidth:0 borderColor:[UIColor clearColor]];
            [self.startSearchButton setTitle:@"" forState:UIControlStateNormal];
            self.progressSuperView.hidden = NO;
        }
            break;
        default:
            break;
    }
}


- (IBAction)searchButtonClick:(id)sender {
    if ([LGCentralManager sharedInstance].isScanning) {
        //        [self endScanPeripherals];
    }else {
        [self startScanPeripherals];
    }
}

- (void)startRotaionImageView {
    if (self.stopRotation) {
        return;
    }
    __weak typeof(self) weakSelf = self;
    [UIView animateWithDuration:0.05 animations:^{
        weakSelf.rotionImageView.transform = CGAffineTransformRotate(weakSelf.rotionImageView.transform, M_PI_4/6);
    } completion:^(BOOL finished) {
        [weakSelf startRotaionImageView];
    }];
}

// 开始搜索设备
- (void)startScanPeripherals {
//    self.rotionImageView.hidden = NO;
//    [self.startSearchButton setTitle:@"Searching" forState:UIControlStateNormal];
//    [self.centerView clipsCornerRadius:kCenterViewWidth * 0.5 borderWidth:0 borderColor:[UIColor clearColor]];
//    self.stopRotation = NO;
//    [self startRotaionImageView];
    self.searchState = kSearchStateScan;
    [[YFCommunicationManager shareInstance] startScanPeripheralsWithBlock:^(NSArray *peripherals, NSError *error) {
        NSArray *peripheralArr = [peripherals sortedArrayUsingComparator:^NSComparisonResult(LGPeripheral *obj1, LGPeripheral *obj2) {
            return obj1.countOfSignal < obj2.countOfSignal;
        }];
        self.lgPeripherals = peripheralArr;
        if ([YFCommunicationManager shareInstance].lgCenterManager.isScanning) {
            [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationFade];
        }
    }];
}

// 结束搜索设备
- (void)endScanPeripherals {
//    self.stopRotation = YES;
//    [self.startSearchButton setTitle:@"Searching" forState:UIControlStateNormal];
//    [self.centerView clipsCornerRadius:kCenterViewWidth * 0.5 borderWidth:4 borderColor:kYellowGreenColor];
//    self.rotionImageView.hidden = YES;
    self.searchState = kSearchStateStopScan;
    [[YFCommunicationManager shareInstance] stopScanningPeripherals];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.lgPeripherals.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    YFSearchViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIndentifer];
    LGPeripheral *per = [self.lgPeripherals objectAtIndex:indexPath.row];
    [cell configerCellWithPerName:per.name isSelect:[self.selectPeriperal.name isEqualToString:per.name]];
    return cell;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    YFSectionHeadView *headView = [YFSectionHeadView sectionHeadView];
    [headView sectionHeadViewWithTitle:@"Connect your device" buttonTitle:@"" showRightBtn:NO];
    return headView;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 58;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // 连接
    LGPeripheral *per = [self.lgPeripherals objectAtIndex:indexPath.row];
    self.selectPeriperal = per;
    [tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
    [self connectThePeripheral:per];
}

#pragma mark - 设备连接
- (void)connectThePeripheral:(LGPeripheral *)peripheral {
    [self endScanPeripherals];
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [[YFSensorManager shareSensorManager] connectThePeripheral:peripheral completed:^(BOOL success, NSError *error) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if (success) {
            // 3.同步数据
            self.searchState = kSearchStateSysData;
            [self synchronBlueHomePageDataCompleated:^{
                // 吐司提示
                [MBProgressHUD showSuccessHudInView:self.view message:@"Synchronizing Completed" afterDelay:1.5];
                // 4.同步完成退出到主页面
                [self.navigationController performSelector:@selector(popViewControllerAnimated:) withObject:@(YES) afterDelay:1.5];
            }];
        }else {
            if (error.code == kYFBleTimeOutErrorCode) {
                
            }else {
                [MBProgressHUD showFailHudInView:self.view message:@"Connect Fail" afterDelay:1.5];
            }
            [self startScanPeripherals];
        }
    }];
}

// 设备连接成功后开始同步数据
- (void)synchronBlueHomePageDataCompleated:(void(^)(void))completed {
    __weak typeof(self) weakSelf = self;
    [[YFSensorManager shareSensorManager] getBlueHomeDataWithComplete:^(NSArray<YFDayRecordItem *> *sportRecordItems, NSError *error) {
        if (error == nil) {
            // 读取详情数据
            [[YFSensorManager shareSensorManager] syncSwingDayDetailDataWithDayItems:sportRecordItems everydayProgress:^(YFDayRecordItem *dayItem, CGFloat dayProgress) {
                
            } allDayProgress:^(CGFloat totalProgress) {
                // 更新进度
                [weakSelf.progressView setCurrent:@(round(totalProgress * 100))];
                [weakSelf.progressView strokeChart];
            } compelete:^{
                [weakSelf.progressView setCurrent:@(100)];
                if (completed) {
                     completed();
                }
            }];
        }else {
            if (completed) {
                completed();
            }
        }
    }];
}


@end
